package com.atguigu.guli.service.oss.controller;

import com.atguigu.guli.service.base.exception.GuliException;
import com.atguigu.guli.service.base.result.R;
import com.atguigu.guli.service.base.result.ResultCodeEnum;
import com.atguigu.guli.service.oss.service.FileService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.exception.ExceptionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.List;
import java.util.concurrent.TimeUnit;

@Api(tags = "阿里云文件管理")
@Slf4j
 //跨域
@RestController
@RequestMapping("/admin/oss/file")
public class FileController {

    @Autowired
    private FileService fileService;

    @ApiOperation(value = "测试")
    @GetMapping("test")
    public R test(){

        //休眠
        try{ TimeUnit.SECONDS.sleep(3); }catch (Exception e){ e.printStackTrace(); }

        log.info("oss test被调用");
        return R.ok();
    }

    /**
     * 文件上传
     * @param file
     */
    @ApiOperation("文件上传")
    @PostMapping("upload")
    public R uploadFile(  //上传文件要保存的桶内目录
            @ApiParam(value = "文件", required = true)
            @RequestParam("file") MultipartFile file,

            @ApiParam(value = "模块", required = true)
            @RequestParam("module") String module) throws IOException {

        try {
            String path = fileService.uploadFile(file , module);
            return R.ok().data("path" , path);
        } catch (Exception e) {
            log.error(ExceptionUtils.getStackTrace(e));
            throw new GuliException(ResultCodeEnum.FILE_UPLOAD_ERROR);
        }

       /* InputStream inputStream = file.getInputStream();
        String originalFilename = file.getOriginalFilename();
        String uploadUrl = fileService.uploadFile(inputStream, module, originalFilename);*/


        //返回r对象
        /*return R.ok().message("文件上传成功").data("url", uploadUrl);*/
    }

    //2、删除文件
    @ApiOperation("删除文件")
    @DeleteMapping("delete")
    //参数1：文件路径  参数2：文件在桶内的目录名称
    public R deleteFile(@RequestParam("path") String path ,
                        @RequestParam("module") String module ){
        fileService.deleteFile(path , module);
        return R.ok();
    }

    //3、批量删除文件
    @DeleteMapping("batchDelete")
    public R batchDelete(@RequestBody List<String> pathList,
                         @RequestParam("module") String module){
        fileService.batchDelete(pathList,module);
        return R.ok();
    }
}